<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router'
import { NEmpty, NIcon, NCard, NButton, NFlex, NAlert } from 'naive-ui';
import { LOG_WX } from "../service/apis/apis";
import SvgIcon from '../components/SvgIcon.vue';
import { type LocationQueryValue } from 'vue-router';
import { useCounterStore } from './../stores/counter'
const counterStore = useCounterStore()
const router = useRouter()
const route = useRoute()
const loginSuccess = ref(true)
const errorMessage = ref('')


onMounted(() => {
    console.log('进入微信扫码界面', route.query)
    const { code, state } = route.query
    if (code && state) {
        console.log('扫码成功', code, state);
        wxlogin(code)
    } else {
        loginSuccess.value = false
    }
})

const wxlogin = (code: string | LocationQueryValue[]) => {
    LOG_WX({ params: JSON.stringify({ code }) }).then((res: any) => {
        console.log('登录返回结果', res);
        if (res.stacode == 200) {
            counterStore.setToken(res.data.token)
            counterStore.setInfo(res.data.userinfo)
            counterStore.login
            if (res.data.reset_password) {
                counterStore.setInitialUser
                router.push('setting')
            } else {
                counterStore.setNotInitialUser
                router.push('application')
            }
        } else {
            loginSuccess.value = false
            errorMessage.value = res.message
        }
    }).catch((err) => {
        loginSuccess.value = false
        errorMessage.value = err.message
    });
}
</script>

<template>
    <NFlex justify="space-between" style=" border: 0px solid #ff1111; width: 100vw;height: 100vh;">
        <n-flex style="border: 0px solid #ff1111;">
            <div></div>
        </n-flex>
        <n-flex vertical justify="center" style="border: 0px solid #ff1111;">
            <n-card style="width: calc(100vw / 4);height: calc(100vh / 2);">
                <div style="margin-top: 150px;">
                    <n-empty v-if="loginSuccess" description="正在进入AI数字化智慧平台...">
                        <template #icon>
                            <n-icon>
                                <SvgIcon iconClass="zhinengAI"></SvgIcon>
                            </n-icon>
                        </template>
                    </n-empty>
                    <div v-else style="text-align: center;">
                        <n-alert title="登录失败" type="warning" style="margin: 30px; ">{{ errorMessage }}</n-alert>
                        <n-button type="primary" @click="router.push('login')" style="margin-top: 10px;">
                            返回登录页面
                        </n-button>
                    </div>
                </div>
            </n-card>
        </n-flex>
        <n-flex style="border: 0px solid #eee;">
            <div> </div>
        </n-flex>
    </NFlex>
</template>
